package com.ybwh.datasource.refreshable.spring.boot;

import com.ybwh.datasource.refreshable.core.datasource.AbstractDelegatedRefreshDataSource;
import io.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;
import io.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource;
import lombok.Getter;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * <p>
 * 可刷新的shardingJdbc3的ShardingDataSource实现
 * </p>
 *
 * @author fanbeibei
 * @version V1.0
 * @since 2019/4/8 15:38
 */
@Getter
public class RefreshableShardingDataSource extends AbstractDelegatedRefreshDataSource {

    private SpringBootConfiguration springBootConfiguration;

    public RefreshableShardingDataSource(SpringBootConfiguration springBootConfiguration) {
        this.springBootConfiguration = springBootConfiguration;
        init();
    }

    @Override
    protected DataSource createDataSource() throws SQLException {
        return ShardingDataSourceFactory.createDataSource(springBootConfiguration.getDataSourceMap(),
                springBootConfiguration.getShardingProperties().getShardingRuleConfiguration(),
                springBootConfiguration.getConfigMapProperties().getConfigMap(),
                springBootConfiguration.getPropMapProperties().getProps());
    }

    @Override
    protected void destroyDataSource(DataSource dataSource) throws Exception {
        ShardingDataSource shardingDataSource = (ShardingDataSource) dataSource;
        shardingDataSource.close();
    }

    @Override
    public void beforeRefresh() {
        springBootConfiguration.setDataSourceMap(springBootConfiguration.getEnvironment());
    }

    @Override
    public void afterRefresh() {

    }
}
